package com.bookstore.controller;

import com.bookstore.entity.Book;
import com.bookstore.service.impl.BookServiceImpl;
import com.bookstore.tools.ExcelUtil;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Author Cofe
 * @Date 2022/5/19 15:00
 */
@Controller
@RequestMapping("/excel")
public class ExcelController {

    @Resource
    private BookServiceImpl bsi;

    @RequestMapping(value = "/exportLesson")
    @ResponseBody
    @CrossOrigin
    public void exportLes(HttpServletResponse response) throws Exception {
        //获取数据
        List<Book> list = bsi.findAllBook();
        //excel标题

        String[] title = {"编号", "图书名", "图书类型", "库存","销量","价格","会员价","浏览量"};
        //excel文件名
        String fileName = System.currentTimeMillis() + ".xls";
        //sheet名
        String sheetName = "图书信息表";
        //没有数据就传入null吧，Excel工具类有对null判断
        String [][] content = null;
        if (list != null && list.size() > 0){
            content = new String[list.size()][title.length];
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            for (int i = 0; i < list.size(); i++) {
                content[i] = new String[title.length];
                Book obj = list.get(i);
                content[i][0] = obj.getBid()+"";
                content[i][1] = obj.getBook_name();
                content[i][2] = obj.getBook_type();
                content[i][3] = obj.getBook_number()+"";
                content[i][4] = obj.getBook_sale()+"";
                content[i][5] = obj.getBook_balance()+"";
                content[i][6] = obj.getBook_membalance()+"";
                content[i][7] = obj.getBook_look()+"";
            }
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content);

        //响应到客户端
        try {
            fileName = new String(fileName.getBytes(), "UTF-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
